using System;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Configuration.Install;

namespace CoadTools.SetupCustomActions
{
	// Example: http://msdn2.microsoft.com/en-us/library/9cdb5eda.aspx
	// Property Reference: http://msdn2.microsoft.com/en-us/aa370905.aspx
	//
	// /RunProc="[ARPHELPLINK]" /Args=""
	// /RunProc="[ProgramFilesFolder]\WinKey\WinKey.exe" /Args=""

	[RunInstaller(true)]
	public partial class RunProc : Installer
	{
		#region Constructor
		public RunProc()
		{ InitializeComponent(); }
		private void InitializeComponent() { }
		#endregion

		#region Overriden Methods
		public override void Uninstall(System.Collections.IDictionary savedState)
		{
			base.Uninstall(savedState);
			RunActions();
		}
		public override void Rollback(System.Collections.IDictionary savedState)
		{
			base.Rollback(savedState);
			RunActions();
		}
		public override void Install(System.Collections.IDictionary stateSaver)
		{
			base.Install(stateSaver);
			RunActions();
		}
		public override void Commit(System.Collections.IDictionary savedState)
		{
			base.Commit(savedState);
			RunActions();
		}
		#endregion
		
		public void RunActions()
		{
			string DeleteFile = this.Context.Parameters["DeleteFile"] + "";
			string CopyFile = this.Context.Parameters["CopyFile"] + "";

			if (CopyFile.Length > 0) File.Copy(CopyFile, this.Context.Parameters["TargetFile"]);
			else if (DeleteFile.Length > 0)
			{
				if (File.Exists(DeleteFile))
				{
					try { File.Delete(DeleteFile); }
					catch (IOException) { }
				}
			}
			else
			{
				string RunProc = this.Context.Parameters["RunProc"] + "";
				string ShortcutPath = this.Context.Parameters["ShortcutPath"] + "";
				string args = this.Context.Parameters["Args"] + "";
				if (RunProc.Length > 0)
				{
					if (ShortcutPath.Length == 0) Process.Start(RunProc, args);
					else
					{
						//Process.Start("iexplore.exe", String.Format("about:'{0}' '{1}' '{2}'", ShortcutPath, RunProc, args));
						//ShellShortcut shortcut = new ShellShortcut(ShortcutPath);
						//shortcut.Path = RunProc;
						//shortcut.Arguments = args;
						//shortcut.Save();
						IWshRuntimeLibrary.WshShell wsh = new IWshRuntimeLibrary.WshShellClass();
						IWshRuntimeLibrary.WshShortcut shortcut = wsh.CreateShortcut(ShortcutPath) as IWshRuntimeLibrary.WshShortcut;
						shortcut.Arguments = args;
						shortcut.TargetPath = RunProc;
						shortcut.IconLocation = Path.GetFileName(RunProc) + ",0";
						shortcut.Save();
					}
				}
			}
		}
	}
}